#encoding=utf-8
#将view需要的共同模块进行封装到一个文件
from utils.common_import import *
from .model import JobStopSchema, JobSearchSchema
from app.dashboard.model import PlatformUsers
from utils.ext import inner_db

class PaiJobs(Resource):
    def __init__(self, *args, **kwargs):
        self.task_client = cluster_client.task_client
        super(PaiJobs, self).__init__(*args, **kwargs)


    # @jwt_required()
    @request_arg_check(JobSearchSchema(), many=False, location="args")
    @exception_response()
    def get(self):
        #判断是否为根据关键字查询
        if "search_multi_key" in current_schema_instance:
            search_multi_key = current_schema_instance["search_multi_key"]
            jobs_list = self.task_client.get_jobs_list_by_key(search_multi_key)
        else:
            jobs_list = self.task_client.list_jobs()

        #没有获取到任务
        if "errors" in jobs_list or "error" in jobs_list:
            logger.info(jobs_list)
            return make_success_response([])

        #限制展示的任务数量
        if len(jobs_list) >= 500:
            jobs_list = jobs_list[1:500]

        user_map = {}
        for job_info in jobs_list:
            if "username" in job_info:
                continue
            if not user_map:
                    user_map = self._get_userid_map()
            if job_info["userId"] not in user_map:
                logger.warning("not find userid:{} info".format(job_info["userId"]))
                continue
            job_info["username"] = user_map[job_info["userId"]]['email']

        return make_success_response(jobs_list)

    def _get_userid_map(self):
        #user_id 转account
        users_info = inner_db.session.query(PlatformUsers.id, PlatformUsers.account, PlatformUsers.email).all()
        user_account_map = {}

        for user_info in users_info:
            user_id = user_info[0]
            account = user_info[1]
            email = user_info[2]
            user_account_map[user_id] = dict(account=account, email=email)

        return user_account_map

class PaiJob(Resource):
    def __init__(self,*args, **kwargs):
        self.task_client = cluster_client.task_client
        super(PaiJob, self).__init__(*args, **kwargs)

    # @jwt_required()
    @exception_response()
    def get(self, job_name):
        #获取集群所有任务
        job_detail = self.task_client.get_job_detail(job_name)

        return make_success_response(job_detail)

    # @jwt_required()
    @permission_auth("admin")
    @request_arg_check(JobStopSchema(), many=False)
    @exception_response()
    def put(self, job_name):
        #获取集群所有任务
        self.task_client.stop_job(job_name)

        return make_no_data_response(status=200, code=0, message="stop job:{} successfully".format(job_name))
